package com.bms.client.exceptionHandler;

/**
 * @author zcx
 * @version 1.0
 * @description ExceptionHandler.java
 * @date 2021/3/22 19:42
 */

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@ResponseBody
public class ExceptionControllerAdvice {
    @ExceptionHandler
    @ResponseBody
    public Map<String, Object> check(Exception e) {
        Map<String, Object> map = new HashMap<>();
        e.printStackTrace();
        String message = "后台服务异常";
        if(e instanceof MethodArgumentNotValidException){
            message=e.getMessage();
            message=message.substring(message.lastIndexOf("default message")+16);
        }
        if(e instanceof HttpMessageNotReadableException){
            message="json格式类型不匹配，请检查您传入的参数";
        }
        if(e instanceof NumberFormatException){
            message="数字格式异常";
        }
        if(e instanceof MethodArgumentTypeMismatchException){
            message=e.getMessage();
            message="传参失败检查参数格式:"+message.substring(message.lastIndexOf("For input string"));
        }
        if(e instanceof MissingServletRequestParameterException){
            message="传参失败检查参数格式是否一致";
        }
        map.put("code",415);
        map.put("msg", message);
        return map;
    }
}

